import { Flex, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import orchestrationService from '@/api/services/orchestrationService';
import { GetWorkBenhList } from '@/common';
import { AppCreateTypeEnum, AppWorkbenchType } from '@/common/app/constants';
import useWindowWidth from '@/hooks/event/use-window-width';
import SharelinkModal from '@/pages/share-link-manage/components/SharelinkModal';
import { useDatasetStore } from '@/store/datasetStore';
import { useUserInfo } from '@/store/userStore';
import { formatDataNoTime } from '@/utils/time';

import { SvgIcon } from '../icon';
import AppInfoModal from '../work-modal/components/AppInfoModal';
import AvatarDisplay from '../work-modal/components/AvatarDisplay';
import NewAgentModeModal from '../work-modal/components/NewAgentModeModal';
import '../work-modal/work.scss';

interface Props {
  type: string; // manager,public, market
  dataList: Array<GetWorkBenhList>;

  onScroll?: () => void;
  changeCollect?: (data: GetWorkBenhList, e: React.MouseEvent) => void;
  flag?: boolean;
  setflag?: (data: boolean) => void;
  height?: number;
  isGetFusion?: boolean;
  onGetFusionCollect?: (data: GetWorkBenhList) => void;
}

export default function FusionBox({
  type,
  onScroll,
  flag,
  setflag = () => {},
  height,
  dataList,
  isGetFusion,
  changeCollect = () => {},
  onGetFusionCollect = () => {},
}: Props) {
  const [isShow, setIsShow] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [searchIndex, setSearchIndex] = useState<number>(0);
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [onOpen, setOnOpen] = useState<boolean>(false);
  const [blangTitle, setBlangTitle] = useState<string>('');
  const [openedDropdownId, setOpenedDropdownId] = useState<number | null>(null);
  const router = useNavigate();
  const [workItems, setWorkItems] = useState<GetWorkBenhList>();
  const [searchText, setSearchText] = useState<string>('');
  const { isPc } = useWindowWidth();
  const { role } = useUserInfo();
  const [template, setTemplate] = useState<any>({});
  const [allDataList, setAllDataList] = useState<Array<GetWorkBenhList>>([]);

  const [newAgentOpen, setNewAgentOpen] = useState<boolean>(false);

  // 应用分享
  const [shareModalOpen, setShareModalOpen] = useState<boolean>(false);
  const [currentAppId, setCurrentAppId] = useState<string>('');
  const { loadAllDatasets } = useDatasetStore();
  const { t } = useTranslation();

  useEffect(() => {
    setAllDataList(dataList);
  }, [type, dataList]);

  const baseStyle: React.CSSProperties = {
    width: isPc ? '' : '100%',
    height: 238,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 8,
    border: '1px solid #ffffffe3',
    cursor: 'pointer',
    flexShrink: 0,
    fontWeight: 500,
    background: '#EEF0F4',
  };

  const baseStyle1: React.CSSProperties = {
    width: '100%',
    height: 156,
    borderRadius: 6,
    // padding: '12px 20px ',
    // background: `url(${type === 'market' ? bgPrcture : bgLayer}) no-repeat #F8FAFB center top`,
    background: '#FEFFFF',
    // backgroundSize: type === 'market' ? '100% 50%' : '50% 50%',
    border: `${isPc ? '2px solid #F8FAFB' : '2px solid transparent'} `,
    cursor: 'pointer',
    position: 'relative',
    flexShrink: 0,
  };

  function mouseEvent(e: number) {
    return () => {
      setActiveIndex(e);
    };
  }

  function mouseLeave() {
    return () => {
      setOpenedDropdownId(null);
      setActiveIndex(-1);
    };
  }
  async function goToApplication(e: React.MouseEvent, obj: GetWorkBenhList) {
    console.log('obj', obj);
    if (isGetFusion) {
      onGetFusionCollect(obj);
      return;
    }
    // 公共函数：打开聊天应用
    const openChatApp = (appId: string, shareId: string, type: string) => {
      if (isPc) {
        try {
          const newWindow = window.open(
            type == 'fusion'
              ? `/fusion?appId=${appId}&shareId=${shareId}`
              : `/apps/chat?appId=${appId}&shareId=${shareId}`,
          );
          newWindow && (newWindow.opener = null);
        } catch {
          const link = document.createElement('a');
          link.href =
            type == 'fusion'
              ? `/fusion?appId=${appId}&shareId=${shareId}`
              : `/apps/chat?appId=${appId}&shareId=${shareId}`;
          link.target = '_blank';
          link.rel = 'noopener noreferrer';
          link.click();
        }
      } else {
        // router(`/apps/chat?appId=${appId}&shareId=${shareId}`);
        router(
          type == 'fusion'
            ? `/fusion?appId=${appId}&shareId=${shareId}`
            : `/apps/chat?appId=${appId}&shareId=${shareId}`,
        );
      }
      // router(type == 'fusion' ? `/fusion?appId=${appId}&shareId=${shareId}` : `/apps/chat?appId=${appId}&shareId=${shareId}`);
    };

    if (type === 'manager') {
      // 统一处理管理员路由
      const getShareId = async () => {
        return (
          obj.share_id ||
          (await orchestrationService.getAppDetailV2(obj.app_id, AppWorkbenchType.manage)).share_id
        );
      };

      const shareId = await getShareId();
      obj.app_type === 'workflow'
        ? router(`/app/workflow?appId=${obj.app_id}&shareId=${shareId}`)
        : router(`/apps/orchestration?appId=${obj.app_id}&shareId=${shareId}`);
      return;
    }

    if (type === 'market') {
      goToAssistant(e, obj);
      return;
    }

    if (type === 'public' || type === 'fusion') {
      // 优先使用现有 share_id
      if (obj.share_id) {
        openChatApp(obj.app_id, obj.share_id, obj.app_type);
        return;
      }

      // 不存在时才请求
      const res = await orchestrationService.getAppDetailV2(obj.app_id, AppWorkbenchType.public);
      console.log('res', res);

      if (res.app_id && res.share_id) {
        openChatApp(res.app_id, res.share_id, obj.app_type);
      }
    }
  }

  const handleCancel = () => {
    setIsModalOpen(false);
    setIsShow(false);
  };

  const changeToPage = async (num: number) => {
    setSearchIndex(num);
    setTemplate({});
    switch (num) {
      case 0:
        break;
      case 1:
        // 这里去空白页面
        handleCancel();
        setOnOpen(true); // 打开浮层
        setBlangTitle(AppCreateTypeEnum.agent);
        break;
      case 2:
        // 这里去工作流页面
        handleCancel();
        setOnOpen(true); // 打开浮层
        setBlangTitle(AppCreateTypeEnum.workflow);
        break;
      default:
        // 这里去融合页面
        handleCancel();
        setOnOpen(true); // 打开浮层
        setBlangTitle(AppCreateTypeEnum.fusion);
        break;
    }
  };

  const goToAssistant = async (e: React.MouseEvent, obj: { app_id: string; app_type: string }) => {
    e.stopPropagation();
    setTemplate(obj);
    handleCancel();
    setOnOpen(true);
    if (obj.app_type == 'agent') {
      setBlangTitle(AppCreateTypeEnum.agent);
    }
    if (obj.app_type == 'workflow') {
      setBlangTitle(AppCreateTypeEnum.workflow);
    }
    if (obj.app_type == 'fusion') {
      setBlangTitle(AppCreateTypeEnum.fusion);
    }
  };

  const workAllRef = useRef<HTMLDivElement>(null);

  // 下拉触底操作
  const Scroll = () => {
    if (workAllRef.current) {
      const height1 = workAllRef.current.clientHeight; // 可以得到我们设置的高度 (不包括滚动的高度)
      const height2 = workAllRef.current.scrollTop; // 当滚动时被卷去的高度
      const height3 = workAllRef.current.scrollHeight; // 全部的高度 包括滚动的高度
      if (height1 + height2 + 20 > height3 && !flag) {
        // 当距离底部20 则会触发
        // 加了flag 是为了防止反复触发
        setflag(true);
        // console.log('触发了');
        // 这里进行请求
        onScroll && onScroll();
        // 成功后关闭
        // setTimeout(() => {
        //   setflag(false)
        // }, 1000)
      }
    }
  };

  return (
    <div>
      <div>
        <div
          ref={workAllRef}
          onScroll={Scroll}
          className="workbench-all"
          style={{
            overflowY: 'auto',
            maxHeight:
              role?.code === 'super_admin' || role?.code === 'admin'
                ? // ? `83vh`
                  // : `88vh`,
                  `calc(83vh - ${height}px)`
                : `calc(88vh - ${height}px)`,
          }}
        >
          <div>
            <Flex
              className="grid-row "
              style={
                isPc
                  ? { display: 'flex', justifyItems: 'center', gap: 10 }
                  : { padding: '0 0px', display: 'flex', justifyContent: 'center', gap: 10 }
              }
            >
              {Array.from(allDataList).map((item: any, i) => {
                return (
                  <div
                    key={i}
                    style={
                      // activeIndex === i ? { ...baseStyle1, border: '1px solid #4E87FF' } : { ...baseStyle1 }
                      { ...baseStyle1 }
                    }
                    onMouseEnter={mouseEvent(i)}
                    onClick={(e) => goToApplication(e, item)}
                    onMouseLeave={mouseLeave()}
                    className="boxs box-hover   p-3 px-4 "
                  >
                    <div className="box-border flex items-center justify-between border-t border-t-[#FFFFFF] bg-[#FEFFFF]">
                      <div className="flex w-full items-center">
                        <AvatarDisplay
                          src={item.app_logo}
                          size={40}
                          className="h-[40px] w-[40px]"
                        />
                        <div className="ml-2 w-full">
                          <div className="  flex items-center justify-between">
                            <div className="  mr-2 w-[140px]  text-xs text-text-5">
                              <div className="h-6 min-w-[50px]  truncate text-sm font-bold leading-6">
                                {item.app_name}
                              </div>
                            </div>
                            <div
                              className=" h-[18px] w-[50px] rounded-small px-[6px]  text-center text-xs leading-[18px]"
                              style={
                                item.app_type == 'agent'
                                  ? { background: '#C0F8EF', color: '#00454D' }
                                  : item.app_type == 'workflow'
                                  ? { background: '#E3C7FD', color: '#280976' }
                                  : { background: '#BADEFF', color: '#002379' }
                              }
                            >
                              {item.app_type == 'agent'
                                ? '智能体'
                                : item.app_type == 'workflow'
                                ? '工作流'
                                : '融合应用'}
                            </div>
                          </div>
                          <div className="flex h-5 items-center text-xs">
                            <span className="mt-[1px]  whitespace-nowrap text-[#C9CDD4]">By</span>
                            <div className="ml-2 flex max-w-[10em] items-center text-text-3">
                              <div className="max-w-[6em] truncate">{item.group_name}</div>
                              <div className=" whitespace-nowrap">/</div>
                              <div className="max-w-[6em] truncate"> {item.user_name}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="mt-3 line-clamp-2 h-9 overflow-hidden  text-ellipsis  text-sm text-[#4E5969]">
                      <div className="text text-xs">
                        {item.review_status === 'reject' && '驳回原因:'}
                      </div>
                      {item.review_status === 'reject'
                        ? item.review_description
                        : item.app_description}
                    </div>

                    <div className=" flex h-10 items-center justify-between rounded-md  ">
                      <div className=" text-xs text-text-3">
                        {formatDataNoTime(item.create_time)}
                        <span className="ml-1">更新</span>
                      </div>
                      <div className="h-5">
                        {type === 'fusion' && (
                          <div
                            className="flex items-center"
                            onClick={(e) => {
                              changeCollect(item, e);
                            }}
                          >
                            {item.isCollect ? (
                              <SvgIcon icon={isPc ? 'fusion-sc1' : 'fusion-mobile-sc1'} size={20} />
                            ) : (
                              <SvgIcon icon={isPc ? 'fusion-sc' : 'fusion-mobile-sc'} size={20} />
                            )}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                );
              })}
            </Flex>
          </div>
        </div>
      </div>

      <NewAgentModeModal
        open={newAgentOpen}
        title="选中创建应用模式"
        goToAssistant={goToAssistant}
        goToApplication={goToApplication}
        setWorkItems={setWorkItems}
        changeToPage={changeToPage}
        onCancel={() => {
          setNewAgentOpen(false);
        }}
      />

      <AppInfoModal
        open={onOpen}
        appType={blangTitle}
        title={blangTitle === AppCreateTypeEnum.workflow ? '创建工作流' : '创建应用'}
        defaultAppName={template?.app_name}
        defaultAppDescription={template?.app_description}
        defaultAppLogo={template?.app_logo}
        defaultSceneImage={template?.scene_image} // 从模板中获取
        onOk={async (data) => {
          const res = await orchestrationService.createAppV2({
            app_type:
              blangTitle === AppCreateTypeEnum.workflow
                ? 'workflow'
                : blangTitle === AppCreateTypeEnum.agent
                ? 'agent'
                : 'fusion',
            app_name: data.appName,
            tag: data.tag,
            app_description: data.appDescription,
            app_logo: data.appLogo,
            scene_image: data.sceneImage,
            template_app_id: template?.app_id,
          });

          if (res.app_id) {
            orchestrationService.updateAppImage(res.app_id, {
              logo: data.appLogoList,
              scene: data.sceneImageList,
            });
            if (blangTitle === AppCreateTypeEnum.workflow) {
              router(`/app/workflow?appId=${res.app_id}&shareId=${res.share_id}`);
            } else if (blangTitle === AppCreateTypeEnum.agent) {
              router(`/apps/orchestration?appId=${res.app_id}&shareId=${res.share_id}`);
            } else {
              router(`/apps/orchestration?appId=${res.app_id}&shareId=${res.share_id}`);
            }
          } else {
            message.error('创建失败');
          }
        }}
        onCancel={() => {
          setOnOpen(false);
        }}
      />
      <SharelinkModal
        open={shareModalOpen}
        appIdValue={currentAppId}
        onCancel={() => {
          setShareModalOpen(false);
          setCurrentAppId('');
        }}
        title="创建分享链接"
      />
    </div>
  );
}
